using System;
using System.Linq;

namespace MapperLearing.Mapper_Mine
{
    /// <summary>
    /// 李嘉琪
    /// 用于实现对象属性映射，包含类型转换的逻辑
    /// 主要应用于页面的字符串转换为筛选参数
    /// </summary>
    public static class MapperHelper
    {
        /// <summary>
        /// 基础类型映射与转换，根据参照对象的属性值赋予当前对象，需要属性名相同
        /// </summary>
        /// <typeparam name="T1">当前对象</typeparam>
        /// <typeparam name="T2">参照对象</typeparam>
        /// <param name="type"></param>
        /// <returns></returns>
        public static T1 MapperFromWeb<T1, T2>(this T1 myself, T2 referenceObj)
            where T1 : class
            where T2 : class
        {
            var listRefer = referenceObj.GetType().GetProperties().ToList();
            myself.GetType().GetProperties().ToList().ForEach(it =>
            {
                var temp = listRefer.FirstOrDefault(re => re.Name.Equals(it.Name, StringComparison.CurrentCultureIgnoreCase));
                if (temp != null)
                {
                    try
                    {
                        if (it.PropertyType == typeof(DateTime) || it.PropertyType == typeof(DateTime?))
                        {
                            it.SetValue(myself, temp.GetValue(referenceObj).ToDateTimeOrNull());
                        }
                        else
                        {
                            it.SetValue(myself, temp.GetValue(referenceObj));
                        }

                    }
                    catch { }
                }
            });
            return myself;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defV"></param>
        /// <returns></returns>
        public static DateTime? ToDateTimeOrNull(this object obj)
        {
            DateTime? temp;
            try
            {
                if (obj == null || Convert.ToDateTime(obj) <= new DateTime(1970, 1, 1))
                {
                    temp = null;
                }
                else
                {
                    temp = Convert.ToDateTime(obj);
                }
            }
            catch
            {
                temp = null;
            }
            return temp;
        }
    }
}